package com.xxl.job.executor.protocol;

import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.executor.utils.TransUtils;

public class ModbusTCPProtocol {

    private String ip;

    private int port;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public ModbusTCPProtocol(){

    }

    public ModbusTCPProtocol(String ip,int port) {
        this.ip=ip;
        this.port=port;
    }

    public static String recvModbusData() {

        TCPProtocol tcpProtocol = new TCPProtocol("10.0.5.53", 502);

        if (tcpProtocol.connect()) {
            //初始化采集命令
            byte[] sendInfo = new byte[12];
            sendInfo[0] = 0x00;
            sendInfo[1] = 0x02;
            sendInfo[2] = 0x00;
            sendInfo[3] = 0x00;
            sendInfo[4] = 0x00;
            sendInfo[5] = 0x06;//后面位数
            sendInfo[6] = 0x01;//设备地址
            sendInfo[7] = 0x01;//功能码
            sendInfo[8] = 0x07;//寄存器起始地址 高八位
            sendInfo[9] = (byte) 0xD1;//寄存器起始地址 低八位
            sendInfo[10] = 0x00;//读寄存器数量 高八位
            sendInfo[11] = (byte) 0x0B;//读寄存器数量 低八位

            tcpProtocol.sendData(sendInfo);
            byte[] retByte = tcpProtocol.recvData();

            if (retByte == null || retByte.length <= 0) {
               // XxlJobLogger.log("ModbusTCPProtocol:IP<" + ip + ">,PORT<" + port + ">寄存器：" + sendInfo[8] + "未读取到数据！");
                return null;
            }else{
                String retStr=TransUtils.getBufHexStr(retByte);
                String sendStr = TransUtils.getBufHexStr(sendInfo);
                System.out.println("发送报文 ： " + sendStr);
                System.out.println("接收报文 ： " + retStr);
                String strNum = retStr.substring(10, 12);//第6帧命令长度
                String functionCode = retStr.substring(12, 14);//第7帧功能码

                return Integer.parseInt(retStr.substring(retStr.length()-2),16)+"";
            }
        }
      //  XxlJobLogger.log("ModbusTCPProtocol:IP<" + ip + ">,PORT<" + port + ">连接失败！");
        return null;
    }

    public static void main(String[] args) {
        try {
           String a = recvModbusData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
